<template>
  <div ref="box" class="box">
    <div class="left">
      <div style="margin-top: 15px;width: 280px">
        <el-input
          v-model="filterText"
          placeholder="输入关键字进行搜索"
          style="width: 170px;display: inline-block;margin-left: 10px"
          clearable
        />
        <el-button plain type="primary" style="display: inline-block" @click="changeName">{{ transfer }}</el-button>
      </div>
      <el-tree
        ref="tree"
        :data="data"
        :props="defaultProps"
        node-key="id"
        :default-expanded-keys="defaultKeys"
        :expand-on-click-node="false"
        :highlight-current="true"
        :current-node-key="currentNodekey"
        :filter-node-method="filterNode"
        @node-click="handleNodeClick"
      >
        <span slot-scope="{ node}" class="span-ellipsis">
          <span :title="node.label">{{ node.label }}</span>
        </span>
      </el-tree>
    </div>
    <div class="resize" title="收缩侧边栏" @mouseup="changeIframeDivStyle('none')" @mousedown="changeIframeDivStyle('')">
      ⋮
    </div>
    <div class="mid">
      <div class="iframeDiv" @mousedown="changeIframeDivStyle('none')" />
      <embed height="100%" width="100%" fullscreen="yes" :src="baseApi+dir+encodeURI(src)+'.pdf'" type="application/pdf" frameborder="0">
    </div>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import { getDirectory } from '../../api/help/help'
let moveLen = ''
export default {
  name: 'Help',
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },
  data() {
    return {
      id: '',
      transfer: '目录简称',
      filterText: '',
      dir: '', // 目录
      currentNodekey: '',
      defaultKeys: [],
      src: '',
      data: [],
      list: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  watch: {
    /* filterText监听*/
    filterText(val) {
      this.$nextTick(() => {
        this.$refs.tree.filter(val.trim())
      })
    },
    /* 监听currentNodekey*/
    currentNodekey: {
      handler: function(val) {
        if (val.toString()) {
          this.currentNodekey = val
          this.$nextTick(() => {
            this.$refs.tree.setCurrentKey(val)
          })
        }
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.getHelpDirectory()
    this.$nextTick(function() {
      this.setCurrentNodekey()
    })
  },
  mounted() {
    this.dragControllerDiv()
    this.changeIframeDivStyle('none')
    window.addEventListener('mousewheel', this.handleScroll)
    window.addEventListener('resize', this.reSize)
  },
  beforeDestroy() {
    window.removeEventListener('mousewheel', this.handleScroll)
    window.removeEventListener('resize', this.reSize)
  },
  methods: {
    /* 屏幕缩小放大*/
    reSize() {
      var mid = document.getElementsByClassName('mid')
      var box = document.getElementsByClassName('box')
      var resize = document.getElementsByClassName('resize')
      var left = document.getElementsByClassName('left')
      if (moveLen !== '') {
        resize[0].style.left = moveLen // 设置左侧区域的宽度
        left[0].style.width = moveLen + 'px'
        box[0].style.width = '100%'
        mid[0].style.width = (box[0].clientWidth - moveLen - 10) + 'px'
      } else {
        left[0].style.width = '280px'
        box[0].style.width = '100%'
        mid[0].style.width = 'calc(100% - 290px)'
      }
    },
    /* 鼠标滚动*/
    handleScroll() {
      this.changeIframeDivStyle('none')
    },

    /* 遮罩样式设置*/
    changeIframeDivStyle(display) {
      var iframeDiv = document.getElementsByClassName('iframeDiv')
      iframeDiv[0].style.display = display
    },
    /* 按钮名字*/
    changeName() {
      this.transfer = this.transfer === '目录全称' ? '目录简称' : '目录全称'
      this.defaultProps.label = this.defaultProps.label === 'simName' ? 'name' : 'simName'
    },
    /* 递归查找对应id的节点的第一个叶子节点*/
    findLeaf(arr, id) {
      try {
        arr.forEach(item => {
          if (item.id === id) {
            this.getFirstLeaf(item)
          } else {
            if (item.isDir === true) {
              this.findLeaf(item.children, id)
            }
          }
        })
      } catch (e) {
        console.log('')
      }
    },
    /* 递归查找第一个叶子节点*/
    getFirstLeaf(data) {
      if (data.isDir === true) {
        try {
          data.children.forEach(citem => {
            if (citem.isDir === true) {
              this.getFirstLeaf(citem)
            } else {
              if (this.defaultKeys.length === 0) {
                this.dir = '/file/帮助_1' + citem.path.substring(0, citem.path.lastIndexOf('/') + 1)
                this.src = citem.name
                this.defaultKeys.push(citem.pid)
                this.currentNodekey = citem.id
              }
              throw new Error()
            }
          })
        } catch (e) {
          console.log('')
        }
      } else {
        this.dir = '/file/帮助_1' + data.path.substring(0, data.path.lastIndexOf('/') + 1)
        this.src = data.name
        this.defaultKeys.push(data.pid)
        this.currentNodekey = data.id
      }
    },
    /* 搜索*/
    filterNode(value, data) {
      if (!value) return true
      if (this.transfer === '目录简称') {
        return data.name.indexOf(value) !== -1
      } else if (this.transfer === '目录全称') {
        return data.simName.indexOf(value) !== -1
      }
    },
    /* 递归加工数据加上id及pid及name去后缀*/
    dealData(arr) {
      const myArr = []
      arr.forEach(item => {
        if (item.isDir === true) {
          item.id = item.path
          item.simName = item.name
          item.children.forEach(citem => {
            if (citem.isDir && citem.isDir === true) {
              citem.pid = item.id
              citem.simName = citem.name
            } else {
              citem.pid = item.id
              citem.name = citem.name.split('.pdf')[0]
              citem.simName = citem.name.split('_')[1]
            }
          })
          this.dealData(item.children)
        } else {
          item.id = item.path
          item.name = item.name.split('.pdf')[0]
          item.simName = item.name.split('_')[1] || item.name
        }
        myArr.push(item)
      })
      return myArr
    },
    /* 递归遍历目录数据*/
    treeIterator(tree, val) {
      tree.forEach((node) => {
        if (node.name.split('_')[0] === val) {
          this.id = node.id
          return
        } else {
          node.children && this.treeIterator(node.children, val)
        }
      })
    },
    /* 获取目录*/
    getHelpDirectory() {
      const params = {
        appType: appType
      }
      getDirectory(params).then(data => {
        if (data) {
          this.list.push(data)
          this.data = this.dealData(this.list)
          this.data[0].name = '帮助文档'
          this.data[0].simName = '帮助文档'
          this.data[0].pid = '0'
          if (this.$route.query.library) {
            this.id = ''
            this.treeIterator(this.data, this.$route.query.id)
            if (this.id !== '') {
              this.findLeaf(this.data, this.id)
            } else {
              this.$alert('该族库手册不存在', '提示', {
                confirmButtonText: '确定',
                callback: () => {
                  window.close()
                }
              })
            }
          } else {
            this.findLeaf(this.data, this.$route.query.id)
          }
        }
      })
    },
    /* 设置当前CurrentNodekey*/
    setCurrentNodekey() {
      this.$refs.tree.setCurrentKey(this.currentNodekey)
    },
    /* 点击切换*/
    handleNodeClick(data) {
      if (data.isDir !== true) {
        this.dir = '/file/帮助_1' + data.path.substring(0, data.path.lastIndexOf('/') + 1)
        this.src = data.name
        this.currentNodekey = data.id
      }
    },
    /* 拖拽*/
    dragControllerDiv() {
      var resize = document.getElementsByClassName('resize')
      var left = document.getElementsByClassName('left')
      var mid = document.getElementsByClassName('mid')
      var box = document.getElementsByClassName('box')
      // 鼠标按下事件
      resize[0].onmousedown = function(e) {
        // 颜色改变提醒
        resize[0].style.background = '#818181'
        var startX = e.clientX
        resize[0].left = resize[0].offsetLeft
        // 鼠标拖动事件
        document.onmousemove = function(e) {
          var endX = e.clientX
          moveLen = resize[0].left + (endX - startX) // （endx-startx）=移动的距离。resize[i].left+移动的距离=左边区域最后的宽度
          var maxT = box[0].clientWidth - resize[0].offsetWidth // 容器宽度 - 左边区域的宽度 = 右边区域的宽度
          if (moveLen < 280) moveLen = 280 // 左边区域的最小宽度为280px
          if (moveLen > maxT - 10) moveLen = maxT - 10 // 右边区域最小宽度为10px
          resize[0].style.left = moveLen // 设置左侧区域的宽度
          left[0].style.width = moveLen + 'px'
          mid[0].style.width = (box[0].clientWidth - moveLen - 10) + 'px'
        }
        // 鼠标松开事件
        document.onmouseup = function(evt) {
          // 颜色恢复
          resize[0].style.background = '#d6d6d6'
          document.onmousemove = null
          document.onmouseup = null
          resize[0].releaseCapture && resize[0].releaseCapture() // 当你不在需要继续获得鼠标消息就要应该调用ReleaseCapture()释放掉
        }
        resize[0].setCapture && resize[0].setCapture() // 该函数在属于当前线程的指定窗口里设置鼠标捕获
        return false
      }
    }
  }
}
</script>
<style lang="scss" scoped>
html,body{
  overflow: auto;
}
/* 拖拽相关样式 */
/*包围div样式*/
.box {
  width: 100%;
  height: 100%;
  margin: 0 0px;
  overflow: hidden;
  box-shadow: -1px 9px 10px 3px rgba(0, 0, 0, 0.11);

}
/*左侧div样式*/
.left {
  margin: 0;
  width: 280px;  /*左侧初始化宽度*/
  height: 100%;
  background: var(--el-color-white);
  float: left;
  overflow: auto;
  .el-tree {
    margin-top: 30px;
    background: none !important;
    overflow: auto;
    border: none;
    font-family: normal;
    .span-ellipsis {
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      display: block;
    }
  }
  ::v-deep .el-tree-node.is-current>.el-tree-node__content {
    font-weight: bold;
  }
  .el-tree ::v-deep  .el-icon-caret-right:before {
    font-size: 16px;
    display: block;
    border: 4px solid transparent;
    background-clip: padding-box;
  }
}
/*拖拽区div样式*/
.resize {
  cursor: col-resize;
  float: left;
  position: relative;
  top: 45%;
  background-color: #d6d6d6;
  border-radius: 5px;
  margin-top: -10px;
  width: 10px;
  height: 50px;
  background-size: cover;
  background-position: center;
  font-size: 30px;
  line-height: 50px;
  color: white;
}
/*拖拽区鼠标悬停样式*/
.resize:hover {
  color: #444444;
}
/*右侧div'样式*/
.mid {
  overflow: hidden;
  margin: 0;
  float: left;
  width: calc(100% - 290px);   /*右侧初始化宽度*/
  height: 100%;
  background: #fff;
  box-shadow: -1px 4px 5px 3px rgba(0, 0, 0, 0.11);
}
/* 添加透明遮罩层 */
.iframeDiv {
  width: 100%;
  height: 100%;
  position: fixed;
  z-index: 1;
  overflow: hidden !important;
  filter: alpha(opacity=0);
  opacity: 0;
  background: transparent;
  margin-top: 30px;
}
</style>

